#coding:utf8

import wx
import os
import wx.lib.buttons as wxButton
import wx.dataview as dv
import wx.lib.agw.aui as aui
from wx.lib.splitter import MultiSplitterWindow
from ruler import *
testItemValue = [(1,'2','3','4','5'),(2,'6','7','8','9'),(3,'8','9','1','0')]
testItemValue2 = [(1,'22','33','44','55'),(2,'6','7','8','9'),(3,'8','9','1','10')]

wildcard ="Text file (*.txt)|*.txt|"    \
           "All files (*.*)|*.*"       




class TestModel(dv.PyDataViewIndexListModel):
    '''dataview 数据模型'''

    def __init__(self, data):
        dv.PyDataViewIndexListModel.__init__(self, len(data))
        self.data = data

    # def GetColumnType(self, col):
        # return "string"

    def GetValueByRow(self, row, col):

        return self.data[row][col]


    # def GetCount(self):
        # return len(self.data)

    def Compare(self, item1, item2, col, ascending):
        if not ascending:  # swap sort order?
            item2, item1 = item1, item2
        row1 = self.GetRow(item1)
        row2 = self.GetRow(item2)
        if (self.data[row1][col] <= self.data[row2][col]) == True:
            return -1
        else:
            return 1   

class Tree(wx.Panel):
    def __init__(self, parent,log,resultList):
        wx.Panel.__init__(self, parent, -1)
        self.box = wx.BoxSizer(wx.VERTICAL)


        self.btnbox = wx.BoxSizer(wx.HORIZONTAL)

        self.btnResultOk = wx.Button(self, -1, "测试", size=(80,30))
        self.btnRule = wx.Button(self,-1,"选择规则",size=(80,30))
        self.btnClear = wx.Button(self,-1,"清空缓存",size=(80,30))
        self.stctxt = wx.TextCtrl(self, -1, "  版本号v0.1.4 ", style=wx.TE_PROCESS_ENTER | wx.TE_READONLY)       

        self.stcExtractRule = YamlSTC(self, -1)

        self.stcExtractRule.SetText(open(log).read())
        self.stcExtractRule.EmptyUndoBuffer()
        self.stcExtractRule.Colourise(0, -1)
        self.stcExtractRule.SetMarginType(1, stc.STC_MARGIN_NUMBER)
        self.stcExtractRule.SetMarginWidth(1, 25)  


        self.dvlc = dvlc = dv.DataViewListCtrl(self)
        dvlc.AppendTextColumn('id', width=40)
        dvlc.AppendTextColumn('artist', width=70)
        dvlc.AppendTextColumn('title', width=260)
        dvlc.AppendTextColumn('genre', width=150)
        dvlc.AppendTextColumn('url', width=200)

        for itemvalues in resultList:
            dvlc.AppendItem(itemvalues)  

        self.btnbox.Add(self.stctxt,-1,wx.EXPAND)
        self.btnbox.Add(self.btnResultOk,-1,wx.EXPAND)
        self.btnbox.Add(self.btnRule,-1,wx.EXPAND)
        self.btnbox.Add(self.btnClear,-1,wx.EXPAND)

        self.box.Add(self.stcExtractRule,1,wx.EXPAND)
        self.box.Add(self.btnbox,0,wx.EXPAND)

        self.box.Add(self.dvlc,2,wx.EXPAND)
        self.SetSizer(self.box)




class Frame(wx.Frame):  
    def __init__(self, parent, id, title, size, pos,log,resultList):
        wx.Frame.__init__(self, parent, id, title, size=size, pos=(0, 0))

        
        self.splitter = MultiSplitterWindow(parent=self, style=wx.SP_LIVE_UPDATE)
    
        self.panel1 = wx.Panel(self.splitter, -1)
        self.box = wx.BoxSizer(wx.VERTICAL)
        self.box1 = wx.BoxSizer(wx.HORIZONTAL)
        self.ShowContentCtrl = wx.TextCtrl(self.panel1, -1, "test TextCtrl",
                                               size=(200, 100), style=wx.TE_MULTILINE|wx.TE_RICH2|wx.TE_READONLY)
        self.box.Add(self.ShowContentCtrl, 2, wx.EXPAND)
        
        self.panel1.SetSizer(self.box)        
        
                
        self.panel2 = wx.Panel(self.splitter, -1)    
        self.box2 = wx.BoxSizer(wx.VERTICAL)
        self.fnb = wx.Notebook(self.panel2)
        self.Bind(wx.EVT_CLOSE,self.preserve)

        self.pnl = Tree(self.fnb,"catalog.txt",testItemValue)
        self.pnl2 = Tree(self.fnb,"extract.txt",testItemValue2)

        menuchoice = wx.Menu()
        mbar = wx.MenuBar()
        itemhor = menuchoice.Append(-1,"Split horizontally")
        self.Bind(wx.EVT_MENU,self.chooseright,itemhor)
        itemver=menuchoice.Append(-1,"Split vertically")
        self.Bind(wx.EVT_MENU,self.choosebottom,itemver)
        mbar.Append(menuchoice,"Splitter")
        self.SetMenuBar(mbar)
        

        self.fnb.AddPage(self.pnl,"url抽取规则")
        self.fnb.AddPage(self.pnl2,"正文抽取规则")
        self.Bind(wx.stc.EVT_STC_CHANGE,self.urlChange,self.pnl.stcExtractRule)
        self.Bind(wx.stc.EVT_STC_CHANGE,self.contentChange,self.pnl2.stcExtractRule)
        self.Bind(wx.EVT_BUTTON,self.OnSelectFile,self.pnl.btnRule)
        self.Bind(wx.EVT_BUTTON,self.OnSelectFile2,self.pnl2.btnRule)

        self.pnl.dvlc.Bind(dv.EVT_DATAVIEW_SELECTION_CHANGED,
                           self.OnSelectionChanged)  
        self.pnl2.dvlc.Bind(dv.EVT_DATAVIEW_SELECTION_CHANGED,
                            self.OnSelectionChanged2)
        
        self.box2.Add(self.fnb, -1, wx.EXPAND)
        self.panel2.SetSizerAndFit(self.box2)
        self.splitter.AppendWindow(self.panel2)
        self.splitter.AppendWindow(self.panel1) 
        self.splitter.SetOrientation(wx.HORIZONTAL)  
        self.splitter.SetSashPosition(0,700)
    
    def chooseright(self, event):
        self.splitter.DetachWindow(self.panel1)
        self.splitter.AppendWindow(self.panel1)
        self.splitter.SetOrientation(wx.HORIZONTAL)
        self.splitter.SetSashPosition(0,700)
        
    def choosebottom(self, event):
        self.splitter.DetachWindow(self.panel1)    
        self.splitter.AppendWindow(self.panel1)
        self.splitter.SetOrientation(wx.VERTICAL)
        self.splitter.SetSashPosition(0,700)
        
    def OnSelectFile(self, event):
        dlg = wx.FileDialog(
            self, message="Choose a file",
            defaultDir=os.getcwd(),
            defaultFile="",
            wildcard=wildcard,
            style=wx.FD_OPEN | wx.FD_MULTIPLE |
            wx.FD_CHANGE_DIR | wx.FD_FILE_MUST_EXIST |
                  wx.FD_PREVIEW
        )

        if dlg.ShowModal() == wx.ID_OK:            
            paths = dlg.GetPaths()
            self.pnl.stcExtractRule.SetText(open(paths[0]).read())
        dlg.Destroy()
    def OnSelectFile2(self, event):
        dlg = wx.FileDialog(
            self, message="Choose a file",
            defaultDir=os.getcwd(),
            defaultFile="",
            wildcard=wildcard,
            style=wx.FD_OPEN | wx.FD_MULTIPLE |
            wx.FD_CHANGE_DIR | wx.FD_FILE_MUST_EXIST |
                  wx.FD_PREVIEW
        )

        if dlg.ShowModal() == wx.ID_OK:            
            paths = dlg.GetPaths()
            self.pnl2.stcExtractRule.SetText(open(paths[0]).read())
        dlg.Destroy()    

    def OnSelectionChanged(self, event):
        self.model = TestModel(testItemValue)
        a = self.pnl.dvlc.GetSelection()
        c = self.model.GetRow(a)

        z = self.model.GetValueByRow(c, 0)
        url = self.model.GetValueByRow(c, 4)
        num = self.pnl.dvlc.GetColumnCount()

        content = " "

        column = self.model.GetValueByRow(c, 1)
        MasterStation = self.model.GetValueByRow(c, 2)
        title = self.model.GetValueByRow(c, 3)
        url = self.model.GetValueByRow(c, 4)
        self.ShowContentCtrl.SetValue("artist:" + column + "\n" + "title:" +
                                          MasterStation + "\n" + "genre:" + title + "\n" + "url:" + url)

    def OnSelectionChanged2(self, event):
        self.model = TestModel(testItemValue2)
        a = self.pnl2.dvlc.GetSelection()
        c = self.model.GetRow(a)

        z = self.model.GetValueByRow(c, 0)
        url = self.model.GetValueByRow(c, 4)
        num = self.pnl2.dvlc.GetColumnCount()

        content = " "

        column = self.model.GetValueByRow(c, 1)
        MasterStation = self.model.GetValueByRow(c, 2)
        title = self.model.GetValueByRow(c, 3)
        url = self.model.GetValueByRow(c, 4)
        self.ShowContentCtrl.SetValue("artist:" + column + "\n" + "title:" +
                                           MasterStation + "\n" + "genre:" + title + "\n" + "url:" + url)    
        

    def urlChange(self,event):
        if self.Title == 'url规则抽取助手（正文抓取规则未保存）':
            self.Title = "url规则抽取助手（正文抓取规则 And url规则未保存）"
        elif self.Title == "url规则抽取助手（正文抓取规则 And url规则未保存）":
            pass
        else:
            self.Title="url规则抽取助手（url规则未保存）"
    def contentChange(self,event):
        if self.Title == "url规则抽取助手（url规则未保存）":
            self.Title="url规则抽取助手（正文抓取规则 And url规则未保存）"
        elif self.Title=="url规则抽取助手（正文抓取规则 And url规则未保存）":
            pass
        else:
            self.Title="url规则抽取助手（正文抓取规则未保存）"  

    def preserve(self,event):
        dlg = wx.MessageDialog(
            None, "是否保存规则", '提示！',wx.YES_NO|wx.ICON_QUESTION)
        retCode = dlg.ShowModal()
        if retCode == wx.ID_YES:
            fn = open('catalog.txt', 'w+')
            fn2 = open('extract.txt', "w+")
            leftRule = self.pnl.stcExtractRule.GetText()
            rightRule = self.pnl2.stcExtractRule.GetText()
            fn.writelines(leftRule)
            fn2.writelines(rightRule)
            fn.close()
            fn2.close()            
            self.Destroy()
        else:
            self.Destroy() 




if __name__ == '__main__':
    app = wx.App(False)
    windonwsize = wx.GetClientDisplayRect()
    frame = Frame(parent=None,
                  id=-1,
        title='url规则抽取助手',
        size=(windonwsize[2] / 2, windonwsize[3]),
        pos=(0, 0),
        log='extract.txt',
        resultList=testItemValue)
    frame.Show()
    app.MainLoop()

